<template>
  <div v-if="isVisible" class="modal-overlay" @click="closeModal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h2 class="modal-title">登录</h2>
        <button @click="closeModal" class="close-btn">
          <X :size="20" />
        </button>
      </div>

      <!-- 登录方式切换标签 -->
      <div class="login-tabs">
        <button
          type="button"
          :class="['tab-btn', { active: loginMode === 'password' }]"
          @click="loginMode = 'password'"
        >
          密码登录
        </button>
        <button
          type="button"
          :class="['tab-btn', { active: loginMode === 'code' }]"
          @click="loginMode = 'code'"
        >
          验证码登录
        </button>
      </div>

      <!-- 密码登录表单 -->
      <form v-if="loginMode === 'password'" @submit.prevent="handlePasswordLogin" class="login-form">
        <div class="form-group">
          <label class="form-label">邮箱</label>
          <input
            v-model="formData.email"
            type="email"
            class="form-input"
            placeholder="请输入邮箱"
            required
          />
        </div>

        <div class="form-group">
          <label class="form-label">密码</label>
          <div class="password-input-wrapper">
            <input
              v-model="formData.password"
              :type="showPassword ? 'text' : 'password'"
              class="form-input"
              placeholder="请输入密码"
              required
            />
            <button
              type="button"
              @click="showPassword = !showPassword"
              class="password-toggle"
            >
              <Eye v-if="showPassword" :size="16" />
              <EyeOff v-else :size="16" />
            </button>
          </div>
        </div>

        <div class="forgot-password-wrapper">
          <button type="button" @click="handleForgotPassword" class="forgot-password-btn">
            忘记密码？
          </button>
        </div>

        <div class="form-actions">
          <button
            type="submit"
            :disabled="isLoading"
            class="btn btn-primary btn-full"
          >
            <div v-if="isLoading" class="loading">
              <div class="spinner"></div>
              <span>登录中...</span>
            </div>
            <span v-else>登录</span>
          </button>
        </div>
      </form>

      <!-- 验证码登录表单 -->
      <form v-if="loginMode === 'code'" @submit.prevent="handleCodeLogin" class="login-form">
        <div class="form-group">
          <label class="form-label">邮箱</label>
          <input
            v-model="codeFormData.email"
            type="email"
            class="form-input"
            placeholder="请输入邮箱"
            required
          />
        </div>

        <div class="form-group">
          <label class="form-label">验证码</label>
          <div class="code-input-wrapper">
            <input
              v-model="codeFormData.code"
              type="text"
              class="form-input"
              placeholder="请输入6位验证码"
              maxlength="6"
              required
            />
            <button
              type="button"
              @click="sendCode"
              :disabled="isSendingCode || countdown > 0"
              class="send-code-btn"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
            </button>
          </div>
        </div>

        <div class="form-actions">
          <button
            type="submit"
            :disabled="isLoading"
            class="btn btn-primary btn-full"
          >
            <div v-if="isLoading" class="loading">
              <div class="spinner"></div>
              <span>登录中...</span>
            </div>
            <span v-else>登录</span>
          </button>
        </div>
      </form>

      <div class="form-footer">
        <p>还没有账号？
          <button type="button" @click="switchToRegister" class="link-btn">
            立即注册
          </button>
        </p>
      </div>

      <!-- 忘记密码弹窗 -->
      <div v-if="showForgotPasswordModal" class="forgot-modal-overlay" @click="showForgotPasswordModal = false">
        <div class="forgot-modal-content" @click.stop>
          <div class="forgot-modal-header">
            <h3 class="forgot-modal-title">重置密码</h3>
            <button @click="showForgotPasswordModal = false" class="close-btn">
              <X :size="20" />
            </button>
          </div>

          <form @submit.prevent="handleResetPassword" class="forgot-form">
            <div class="form-group">
              <label class="form-label">邮箱</label>
              <input
                v-model="forgotFormData.email"
                type="email"
                class="form-input"
                placeholder="请输入邮箱"
                required
              />
            </div>

            <div class="form-group">
              <label class="form-label">验证码</label>
              <div class="code-input-wrapper">
                <input
                  v-model="forgotFormData.code"
                  type="text"
                  class="form-input"
                  placeholder="请输入6位验证码"
                  maxlength="6"
                  required
                />
                <button
                  type="button"
                  @click="sendForgotCode"
                  :disabled="isSendingCode || forgotCountdown > 0"
                  class="send-code-btn"
                >
                  {{ forgotCountdown > 0 ? `${forgotCountdown}秒后重试` : '发送验证码' }}
                </button>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">新密码</label>
              <div class="password-input-wrapper">
                <input
                  v-model="forgotFormData.newPassword"
                  :type="showForgotPassword ? 'text' : 'password'"
                  class="form-input"
                  placeholder="请输入新密码（至少6位）"
                  minlength="6"
                  required
                />
                <button
                  type="button"
                  @click="showForgotPassword = !showForgotPassword"
                  class="password-toggle"
                >
                  <Eye v-if="showForgotPassword" :size="16" />
                  <EyeOff v-else :size="16" />
                </button>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">确认密码</label>
              <input
                v-model="forgotFormData.confirmPassword"
                :type="showForgotPassword ? 'text' : 'password'"
                class="form-input"
                placeholder="请再次输入新密码"
                minlength="6"
                required
              />
            </div>

            <div class="form-actions">
              <button
                type="submit"
                :disabled="isLoading"
                class="btn btn-primary btn-full"
              >
                <div v-if="isLoading" class="loading">
                  <div class="spinner"></div>
                  <span>重置中...</span>
                </div>
                <span v-else>确认重置</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useAuthStore } from '../stores/auth'
import { useToast } from 'vue-toastification'
import { X, Eye, EyeOff } from 'lucide-vue-next'

const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close', 'switch-to-register'])

const authStore = useAuthStore()
const toast = useToast()

const isLoading = ref(false)
const isSendingCode = ref(false)
const showPassword = ref(false)
const loginMode = ref('password') // 'password' 或 'code'
const countdown = ref(0)
const showForgotPasswordModal = ref(false)
const showForgotPassword = ref(false) // 控制忘记密码弹窗中的密码可见性
const forgotCountdown = ref(0)

const formData = reactive({
  email: '',
  password: ''
})

const codeFormData = reactive({
  email: '',
  code: ''
})

const forgotFormData = reactive({
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码登录
const handlePasswordLogin = async () => {
  isLoading.value = true
  
  try {
    const result = await authStore.login(formData.email, formData.password)
    
    if (result.success) {
      toast.success(result.message)
      closeModal()
      resetForm()
    } else {
      toast.error(result.message)
    }
  } catch (error) {
    toast.error('登录失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 验证码登录
const handleCodeLogin = async () => {
  isLoading.value = true
  
  try {
    const result = await authStore.emailCodeLogin(codeFormData.email, codeFormData.code)
    
    if (result.success) {
      toast.success(result.message)
      closeModal()
      resetForm()
    } else {
      toast.error(result.message)
    }
  } catch (error) {
    toast.error('登录失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 发送验证码
const sendCode = async () => {
  if (!codeFormData.email) {
    toast.error('请先输入邮箱')
    return
  }
  
  isSendingCode.value = true
  
  try {
    const result = await authStore.sendVerificationCode(codeFormData.email)
    
    if (result.success) {
      toast.success(result.message)
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      toast.error(result.message)
    }
  } catch (error) {
    toast.error('验证码发送失败，请重试')
  } finally {
    isSendingCode.value = false
  }
}

// 处理忘记密码
const handleForgotPassword = () => {
  showForgotPasswordModal.value = true
  forgotFormData.email = formData.email // 预填充邮箱
}

// 发送忘记密码验证码
const sendForgotCode = async () => {
  if (!forgotFormData.email) {
    toast.error('请先输入邮箱')
    return
  }
  
  isSendingCode.value = true
  
  try {
    const result = await authStore.sendVerificationCode(forgotFormData.email)
    
    if (result.success) {
      toast.success(result.message)
      // 开始倒计时
      forgotCountdown.value = 60
      const timer = setInterval(() => {
        forgotCountdown.value--
        if (forgotCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      toast.error(result.message)
    }
  } catch (error) {
    toast.error('验证码发送失败，请重试')
  } finally {
    isSendingCode.value = false
  }
}

// 重置密码
const handleResetPassword = async () => {
  if (!forgotFormData.email || !forgotFormData.code || !forgotFormData.newPassword || !forgotFormData.confirmPassword) {
    toast.error('请填写完整信息')
    return
  }
  
  if (forgotFormData.newPassword !== forgotFormData.confirmPassword) {
    toast.error('两次输入的密码不一致')
    return
  }
  
  if (forgotFormData.newPassword.length < 6) {
    toast.error('密码至少需要6位')
    return
  }
  
  isLoading.value = true
  
  try {
    const result = await authStore.resetPassword(
      forgotFormData.email, 
      forgotFormData.code,
      forgotFormData.newPassword,
      forgotFormData.confirmPassword
    )
    
    if (result.success) {
      toast.success(result.message)
      showForgotPasswordModal.value = false
      forgotFormData.email = ''
      forgotFormData.code = ''
      forgotFormData.newPassword = ''
      forgotFormData.confirmPassword = ''
      forgotCountdown.value = 0
      showForgotPassword.value = false
    } else {
      toast.error(result.message)
    }
  } catch (error) {
    toast.error('密码重置失败，请重试')
  } finally {
    isLoading.value = false
  }
}

const closeModal = () => {
  emit('close')
  resetForm()
}

const switchToRegister = () => {
  emit('switch-to-register')
  resetForm()
}

const resetForm = () => {
  formData.email = ''
  formData.password = ''
  codeFormData.email = ''
  codeFormData.code = ''
  forgotFormData.email = ''
  forgotFormData.code = ''
  forgotFormData.newPassword = ''
  forgotFormData.confirmPassword = ''
  showPassword.value = false
  showForgotPassword.value = false
  countdown.value = 0
  forgotCountdown.value = 0
  loginMode.value = 'password'
  showForgotPasswordModal.value = false
}
</script>

<style scoped>
.modal-overlay {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  background: rgba(0, 0, 0, 0.7);
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  z-index: 99999 !important;
  backdrop-filter: blur(5px);
  padding: 20px !important;
  box-sizing: border-box;
  min-height: 100vh !important;
}

.modal-content {
  background: var(--bg-primary) !important;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-xl);
  padding: var(--spacing-2xl);
  width: 100% !important;
  max-width: 400px !important;
  max-height: 70vh !important;
  overflow-y: auto;
  animation: slideUp 0.3s ease;
  position: relative !important;
  top: auto !important;
  left: auto !important;
  right: auto !important;
  bottom: auto !important;
  transform: none !important;
  margin: auto !important;
  flex-shrink: 0;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-xl);
}

.modal-title {
  font-size: var(--font-size-2xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: var(--spacing-sm);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
}

.close-btn:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.login-tabs {
  display: flex;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-xl);
  border-bottom: 1px solid var(--border-color);
}

.tab-btn {
  flex: 1;
  padding: var(--spacing-md);
  background: none;
  border: none;
  border-bottom: 2px solid transparent;
  color: var(--text-secondary);
  font-size: var(--font-size-base);
  font-weight: 500;
  cursor: pointer;
  transition: all var(--transition-fast);
}

.tab-btn:hover {
  color: var(--text-primary);
}

.tab-btn.active {
  color: var(--primary-color);
  border-bottom-color: var(--primary-color);
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.form-label {
  font-size: var(--font-size-sm);
  font-weight: 500;
  color: var(--text-primary);
}

.form-input {
  padding: var(--spacing-md);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  background: var(--bg-secondary);
  color: var(--text-primary);
  font-size: var(--font-size-base);
  transition: all var(--transition-fast);
}

.form-input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.password-input-wrapper {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: var(--spacing-md);
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: var(--spacing-xs);
  border-radius: var(--radius-sm);
  transition: color var(--transition-fast);
}

.password-toggle:hover {
  color: var(--text-primary);
}

.forgot-password-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--spacing-sm);
}

.forgot-password-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
  cursor: pointer;
  transition: color var(--transition-fast);
}

.forgot-password-btn:hover {
  color: var(--primary-color);
}

.code-input-wrapper {
  position: relative;
  display: flex;
  gap: var(--spacing-sm);
}

.code-input-wrapper .form-input {
  flex: 1;
}

.send-code-btn {
  padding: var(--spacing-md) var(--spacing-lg);
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: var(--radius-md);
  font-size: var(--font-size-sm);
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  transition: all var(--transition-fast);
}

.send-code-btn:hover:not(:disabled) {
  background: var(--primary-hover);
}

.send-code-btn:disabled {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
  cursor: not-allowed;
}

.btn-full {
  width: 100%;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-sm);
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.form-footer {
  text-align: center;
  margin-top: var(--spacing-md);
}

.form-footer p {
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
  margin: 0;
}

.link-btn {
  background: none;
  border: none;
  color: var(--primary-color);
  cursor: pointer;
  font-size: var(--font-size-sm);
  text-decoration: underline;
  transition: color var(--transition-fast);
}

.link-btn:hover {
  color: var(--primary-hover);
}

/* 忘记密码弹窗样式 */
.forgot-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100000;
  animation: fadeIn 0.2s ease;
}

.forgot-modal-content {
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-xl);
  padding: var(--spacing-xl);
  width: 90%;
  max-width: 400px;
  animation: slideUp 0.3s ease;
}

.forgot-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
}

.forgot-modal-title {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.forgot-form {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.forgot-hint {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin: 0;
  padding: var(--spacing-sm);
  background: var(--bg-secondary);
  border-radius: var(--radius-md);
  text-align: center;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* Mobile Styles */
@media (max-width: 768px) {
  .modal-overlay {
    padding: 1rem;
  }
  
  .modal-content {
    padding: var(--spacing-xl);
    max-height: calc(100vh - 2rem);
  }
}
</style>
